package com.woniuxy.kaer.tenants.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.kaer.commons.util.Result;
import com.woniuxy.kaer.service.dto.OrderInfoDto;
import com.woniuxy.kaer.service.feign.ServiceFeignClient;
import com.woniuxy.kaer.tenants.entity.ShopInfo;
import com.woniuxy.kaer.tenants.entity.TransactionLogs;
import com.woniuxy.kaer.tenants.mapper.ShopInfoMapper;
import com.woniuxy.kaer.tenants.mapper.TransactionLogsMapper;
import com.woniuxy.kaer.tenants.param.TurnoverRecordsParam;
import com.woniuxy.kaer.tenants.service.TransactionLogsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年02月17日
 */
@Service
public class TransactionLogsServiceImpl extends ServiceImpl<TransactionLogsMapper, TransactionLogs> implements TransactionLogsService {
    @Resource
    private ServiceFeignClient serviceFeignClient;
    @Resource
    private TransactionLogsMapper transactionLogsMapper;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Override
    public void MerchantRecords(TurnoverRecordsParam param) throws Exception {
        Result<OrderInfoDto> result = serviceFeignClient.getServiceOrderById(param.getServiceOrderId());
        OrderInfoDto orderInfoDto = result.getData();
        if(null==orderInfoDto){
            throw new Exception("订单不存在");
        }
        ShopInfo shopInfo = shopInfoMapper.selectById(orderInfoDto.getShopId());
        if(null==shopInfo){
            throw new Exception("商家不存在");
        }
        TransactionLogs transactionLogs1 = BeanUtil.toBean(param, TransactionLogs.class);
        transactionLogs1.setUpdateTime(LocalDateTime.now());

        //查询最后一条消息
        TransactionLogs transactionLogs = transactionLogsMapper.selectLastTransactionLogs();
        if(null==transactionLogs){
            transactionLogs1.setRevenue(param.getAmount());
        }else {
            transactionLogs1.setRevenue(transactionLogs.getRevenue().add(param.getAmount()));
        }
        transactionLogsMapper.insert(transactionLogs1);
    }
}
